/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.hop.pipeline.transforms.agentscript;

import static javax.xml.parsers.DocumentBuilderFactory.newInstance;

import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.hop.core.annotations.Transform;
import org.apache.hop.core.exception.HopTransformException;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.row.value.ValueMetaString;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.metadata.api.HopMetadataProperty;
import org.apache.hop.metadata.api.IHopMetadataProvider;
import org.apache.hop.pipeline.transform.BaseTransformMeta;
import org.apache.hop.pipeline.transform.ITransformMeta;
import org.apache.hop.pipeline.transform.TransformMeta;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

@Transform(
    id = "agent-llm-script",
    image = "abort.svg",
    name = "Agent-Transforms-Script",
    description = "Executes scripts for JSR-223 Script Engines",
    categoryDescription = "LLM",
    keywords = "script,scripting,groovy,python,javascript,ecmascript,ruby",
    documentationUrl = "/pipeline/transforms/script.html")
public class AgentScriptMetaData extends BaseTransformMeta<AgentScript, AgentScriptData>
    implements ITransformMeta {
  private static final Class<?> PKG = AgentScriptMetaData.class; // For Translator.

  /** Threshold to abort. */
  @HopMetadataProperty(key = "id")
  private String id = "";

  /** Message to put in log when aborting. */
  @HopMetadataProperty(key = "output_message")
  private String outputMessage = "";

  @HopMetadataProperty(key = "input_message")
  private String inputMessage = "";

  public AgentScriptMetaData() {
    logBasic("[AgentScriptMetaData]init ");
  }

  public AgentScriptMetaData(AgentScriptMetaData m) {
    this();
    this.id = m.id;
    this.inputMessage = m.inputMessage;
    this.outputMessage = m.outputMessage;
  }

  @Override
  public AgentScriptMetaData clone() {
    return new AgentScriptMetaData(this);
  }

  @Override
  public void getFields(
      IRowMeta inputRowMeta,
      String name,
      IRowMeta[] info,
      TransformMeta nextTransform,
      IVariables variables,
      IHopMetadataProvider metadataProvider)
      throws HopTransformException {
    // Output fields (String),通过这个函数增加output字段,外部接口可以看到
    String output_name = "output_message";
    logBasic("[getFields]add output ");
    IValueMeta v = new ValueMetaString(output_name);
    v.setLength(100, -1);
    v.setOrigin(name);
    inputRowMeta.addValueMeta(v);

    output_name = "input_message";
    v = new ValueMetaString(output_name);
    v.setLength(100, -1);
    v.setOrigin(name);
    inputRowMeta.addValueMeta(v);
  }

  /**
   * @return
   */
  public String getXmlData(String transformName) {
    System.out.println("[getXmlData]this.id=" + this.id);
    System.out.println("[getXmlData]this.inputMessage=" + this.inputMessage);
    String ret =
        "<root>"
            + String.format("<%s>%s</%s>", "id", this.id, "id")
            + String.format("<%s>%s</%s>", "name", transformName, "name")
            + String.format("<%s>%s</%s>", "input_message", this.inputMessage, "input_message")
            + "</root>";
    return ret;
  }

  /**
   * 设置json对象
   *
   * @param xml 内容的值
   */
  public String setXmlData(String xml) {
    // String xml = "<root><name>11</name><age>10</age></root>";
    String transformName = "AgentScript";
    try {
      System.out.println("[setXmlData]xml=" + xml);
      DocumentBuilderFactory dbf = newInstance();
      dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));

      NodeList nodes = doc.getElementsByTagName("input_message");
      System.out.println("input_message: " + nodes.item(0).getTextContent());
      this.inputMessage = nodes.item(0).getTextContent();

      nodes = doc.getElementsByTagName("id");
      System.out.println("id: " + nodes.item(0).getTextContent());
      this.id = nodes.item(0).getTextContent();

      nodes = doc.getElementsByTagName("name");
      transformName = nodes.item(0).getTextContent();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return transformName;
  }

  public String getId() {
    return id;
  }

  public void setId(String uid) {
    this.id = uid;
  }

  public String getOutputMessage() {
    return outputMessage;
  }

  public void setOutputMessage(String outputMessage) {
    this.outputMessage = outputMessage;
  }

  public String getInputMessage() {
    return inputMessage;
  }

  public void setInputMessage(String inputMessage) {
    this.inputMessage = inputMessage;
  }
}
